package org.sysmhg.base.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.sysmhg.base.dao.CustomerDAO;
import org.sysmhg.base.model.Customer;
import org.sysmhg.util.Pagination;

public class CustomerDAOHibernate extends HibernateDaoSupport implements CustomerDAO{

    @SuppressWarnings("unchecked")
	public List<Customer> getCustomers(Customer customer, Pagination pagination) {
    	Criteria criteria =  getSession().createCriteria(Customer.class);
    	//Total Count
    	criteria.setProjection(Projections.rowCount());
    	pagination.setTotalCount(criteria.uniqueResult());
    	
    	//Pagination
    	criteria.setProjection(null);
    	criteria.setFirstResult(Integer.parseInt(String.valueOf(pagination.getStart())));
    	criteria.setMaxResults(Integer.parseInt(String.valueOf(pagination.getLimit())));
    	
    	if(pagination.getFieldNameSort()!=null){
    		if(pagination.getDirectionSort().equalsIgnoreCase("ASC")){
    			criteria.addOrder(Order.asc(pagination.getFieldNameSort()));
    		}else{
    			criteria.addOrder(Order.desc(pagination.getFieldNameSort()));
    		}
    	}
    	return criteria.list();
    }

    public Customer getCustomer(Customer customer) {
        return (Customer) getHibernateTemplate().get(Customer.class, customer.getCustomer_id());
    }

    public void createCustomer(Customer Customer) {
        getHibernateTemplate().save(Customer);
    }

    public void deleteCustomer(Customer customer) {
    	getHibernateTemplate().delete(customer);
    }

	public void updateCustomer(Customer Customer) {
		getHibernateTemplate().update(Customer);
	}
}